package com.cloudptt.wp.ui.views;

import com.cloudptt.wp.R;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

public class CustomEditText extends EditText {
	
	private Drawable drawablePwdVisible;
	private Drawable drawablePwdInvisible;
	private boolean showPwd = false;
	private Drawable[] drawables;
	private Drawable mRightDrawable;
	
	public CustomEditText(Context context) {
		super(context);
		init(context, null);
		// TODO Auto-generated constructor stub
	}

	public CustomEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
		// TODO Auto-generated constructor stub
	}

//	public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
////		super(context, attrs, defStyleAttr, defStyleRes);
//		init(context, attrs);
//		// TODO Auto-generated constructor stub
//	}

	private void init(Context context, AttributeSet attrs){
		drawablePwdVisible = getResources().getDrawable(R.drawable.pwd_end_icon_visible);
		drawablePwdInvisible = getResources().getDrawable(R.drawable.pwd_end_icon_invisible);
		drawables = getCompoundDrawables();
		mRightDrawable = getCompoundDrawables()[2];
		updateVisible();
	}
	
	private void setPasswordVisible(boolean visible){
		showPwd = visible;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		int xDown = (int) event.getX();
		if(event.getAction() == MotionEvent.ACTION_DOWN && xDown >= (getWidth() - getCompoundPaddingRight() * 2)  && xDown < getWidth()){
			//setPwdVisible or setPwdInvisible
			changeVisibleState();
			return false;
		}
		return super.onTouchEvent(event);
	}
	
	private void changeVisibleState(){
		showPwd = !showPwd;
		updateVisible();
	}
	
	private void updateVisible(){
		if(showPwd){
			setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			mRightDrawable = drawablePwdVisible;
			mRightDrawable.setBounds(0, 0, mRightDrawable.getMinimumWidth(), mRightDrawable.getMinimumHeight());
			setCompoundDrawables(drawables[0], drawables[1], mRightDrawable, drawables[3]);
		}else{
			setTransformationMethod(PasswordTransformationMethod.getInstance());
			mRightDrawable = drawablePwdInvisible;
			mRightDrawable.setBounds(0, 0, mRightDrawable.getMinimumWidth(), mRightDrawable.getMinimumHeight());
			setCompoundDrawables(drawables[0], drawables[1], mRightDrawable, drawables[3]);
		}
		setSelection(getText().length());
	}
}
